# _*_ coding:utf-8 _*_
# @File  : layout.py
# @Time  : 2022-01-19  08:41
# @Author: zizle

import pathlib
from fastapi import APIRouter, Query, Form, UploadFile

from v1_all_api.all_response import AllResponse
from v1_all_api.all_utils import datetime_utils
from configs import FILE_STORAGE, WEB_HOST

layout_api = APIRouter()


@layout_api.get('/')   # 获取期货日报指定日期版面
async def qhrb_layout(date: str = Query(...)):
    query_date = datetime_utils.auth_datetime_string(datetime_string=date, f='%Y-%m-%d')
    if not query_date:
        return AllResponse.validate_error(msg='日期无法格式化为%Y-%m-%d')
    # 查询今日日报版面数据
    prefix_folder = f'QHRB/DailyPdf/{query_date[:4]}/{query_date}/'
    layout_folder = pathlib.Path(FILE_STORAGE).joinpath(prefix_folder)
    response_data = []
    for file in layout_folder.glob('*.pdf'):
        layout_name = file.name.replace(query_date+'-', '').replace('.pdf', '')
        filepath = WEB_HOST + prefix_folder + file.name
        response_data.append({'layout': layout_name, 'filepath': filepath})
    return AllResponse.operate_successfully(data=response_data)


@layout_api.post('/')  # 上传期货日报的版面文件
async def save_qhrb_layout(date: str = Form(...), layout_file: UploadFile = Form(...)):
    save_date = datetime_utils.auth_datetime_string(date, f='%Y-%m-%d')
    if not save_date:
        return AllResponse.validate_error(msg='日期无法格式化为%Y-%m-%d')
    prefix_folder = f'QHRB/DailyPdf/{save_date[:4]}/{save_date}'
    layout_folder = pathlib.Path(FILE_STORAGE).joinpath(prefix_folder)
    if not layout_folder.exists():
        layout_folder.mkdir(parents=True)
    filepath = layout_folder.joinpath(layout_file.filename)
    with open(filepath, 'wb') as fp:
        file_content = await layout_file.read()
        fp.write(file_content)
    return AllResponse.create_successfully(msg='版面文件保存成功!')

